<template>
  <el-upload
    class="upload-demo"
    :action="this.$http.adornUrl('/sms/upload/file')"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :before-remove="beforeRemove"
    multiple
    :limit="limitSize"
    :on-exceed="handleExceed"
    :file-list="fileList"
    :before-upload="beforeUpload"
    :on-success="handleSuccess"
    :data="dataObj"
  >
    <el-button size="small" type="primary">点击上传</el-button>
    <div slot="tip" class="el-upload__tip">只能上传nes文件，且不超过50MB</div>
  </el-upload>
</template>
<script>
export default {
  props: ["url", "limit"],
  data() {
    return {
      fileList: [],
      dataObj: {},
      limitSize:this.limit
    };
  },
  watch: {
    url:function(newVal,val){
      if(newVal && !val){
         if(this.fileList.length==0){
            this.fileList.push({name: '已上传nes文件', url:newVal})
         }      
      }
      if(!newVal){
          this.fileList = []
      }
    }
  },
  methods: {
    handleRemove(file, fileList) {
      console.log("handleRemove",file, fileList);
    },
    handlePreview(file) {
      console.log("handlePreview",file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 ${this.limitSize} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    beforeRemove(file, fileList) {
    //   return this.$confirm(`确定移除 ${file.name}？`);
     console.log("file",file);
      this.$emit("handleUpdateFile",null)
      return true
    },

    handleSuccess(res, file) {
      console.log(res,"上传成功");
      if (res.url) {
        var url = this.$http.imgUrl(res.url);
        this.$emit("handleUpdateFile",url)
      }
    },

    beforeUpload(file) {
      this.dataObj.uploadType = 2;
      
      let nameArr = file.name.split(".")
      const isJPG = nameArr[nameArr.length-1] === "nes";
      const isLt2M = file.size / 1024 / 1024 < 50;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 nes 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 50MB!");
      }
      return isJPG && isLt2M;
    },
  },
};
</script>